﻿using System.Collections.Concurrent;
using TrackSystem.Entities.Models;
using TrackSystem.IO.Models;

namespace TrackSystem.IO.Ports
{
    /// <summary>
    /// 端口管理
    /// </summary>
    public class PortFactory
    {
        public static PortFactory Instance;

        public ConcurrentDictionary<string, PortItem> Items;
        public ConcurrentDictionary<int, string> IdNameDictionary;

        static PortFactory()
        {
            Instance = new PortFactory();
            Instance.Initialize();
        }

        private void Initialize()
        {
            Items = new();
            IdNameDictionary = new();
            Items.Clear();
        }

        /// <summary>
        /// 释放所有资源
        /// </summary>
        public void Disposable()
        {
            foreach (var item in Items.Values)
            {
                item.Disposable();
            }
            Items.Clear();
            IdNameDictionary.Clear();
        }

        public bool Insert(ChannelTable channel, ProtocolBase sensor)
        {

            if (!Items.ContainsKey(channel.Name)) {
                var item = new PortItem(channel);
                Items.TryAdd(channel.Name, item);
                IdNameDictionary.TryAdd(channel.Id, channel.Name);
            }

            Items[channel.Name].InsertSensor(sensor);
            return true;
        }

    }
}
